package com.hgd.security.evp.auth.interceptor;

import com.hgd.security.evp.auth.entity.CustomUserDetails;
import com.hgd.security.evp.common.context.CurrentContext;
import com.hgd.security.evp.common.util.EmptyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户token拦截认证
 *
 * @author scp
 * @version 1.0
 */
public class UserAuthRestInterceptor extends HandlerInterceptorAdapter {

    private Logger logger = LoggerFactory.getLogger(UserAuthRestInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        CustomUserDetails userDetails = null;

        if(EmptyUtil.isNotEmpty(authentication)){
            Object principal = authentication.getPrincipal();

            if (principal instanceof CustomUserDetails) {
                userDetails = (CustomUserDetails) principal;
                CurrentContext.setEAccount(userDetails.getUsername());
                CurrentContext.setUserName(userDetails.getUserName());
                CurrentContext.setUserId(userDetails.getUserId() == null ? null : String.valueOf(userDetails.getUserId()));
                CurrentContext.setDeptId(userDetails.getDeptId() == null ? null : String.valueOf(userDetails.getDeptId()));
                CurrentContext.setTenantId(userDetails.getTenantId());
            }

        }

        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
        throws Exception {
        CurrentContext.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
